package com.itheima.bos.service.take_delivery.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.QueryStringQueryBuilder.Operator;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.itheima.bos.dao.take_delivery.WayBillRepository;
import com.itheima.bos.domain.take_delivery.WayBill;
import com.itheima.bos.index.WayBillIndexRepository;
import com.itheima.bos.service.take_delivery.WayBillService;

@Service
@Transactional
public class WayBillServiceImpl implements WayBillService {

	@Autowired
	private WayBillRepository wayBillRepository;

	@Autowired
	private WayBillIndexRepository wayBillIndexRepository;

	@Override
	public void save(WayBill model) {
		/*
		 * 先判断运单中是否已存在运单号,存在则更新
		 */
		/*
		 * WayBill persistWayBill =
		 * wayBillRepository.findByWayBillNum(model.getWayBillNum());
		 * 
		 * if (persistWayBill == null || persistWayBill.getId() == null) {
		 * wayBillRepository.save(model); } else { try { Integer id =
		 * persistWayBill.getId(); BeanUtils.copyProperties(persistWayBill,
		 * model); persistWayBill.setId(id); } catch (Exception e) {
		 * 
		 * e.printStackTrace(); throw new RuntimeException(); } }
		 */
		WayBill persistWayBill = wayBillRepository.findByWayBillNum(model.getWayBillNum());
		// 即第一次录入运单
		if (persistWayBill == null || persistWayBill.getId() == null) {
			model.setSignStatus(1);
			wayBillRepository.save(model);
			// 保存索引
			wayBillIndexRepository.save(model);
		} else {
			// 即更新操作
			if (persistWayBill.getSignStatus() == 1) {
				wayBillRepository.save(model);
				// 保存索引
				wayBillIndexRepository.save(model);
			} else {
				throw new RuntimeException("运单已发出,无法修改保存");
			}
		}
	}

	@Override
	public Page<WayBill> findPageData(WayBill wayBill, Pageable pageable) {

		// 判断WayBill 中条件是否存在
		if (StringUtils.isBlank(wayBill.getWayBillNum()) && StringUtils.isBlank(wayBill.getSendAddress())
				&& StringUtils.isBlank(wayBill.getRecAddress()) && StringUtils.isBlank(wayBill.getSendProNum())
				&& (wayBill.getSignStatus() == null || wayBill.getSignStatus() == 0)) {
			// 无条件查询 、查询数据库
			return wayBillRepository.findAll(pageable);
		} else {
			// 无条件查询,查询索引库
			// 查询条件
			// must 条件必须成立 and
			// must not 条件必须不成立 not
			// should 条件可以成立 or
			BoolQueryBuilder query = new BoolQueryBuilder(); // 布尔查询 ，多条件组合查询
			// 向组合查询对象添加条件
			if (StringUtils.isNoneBlank(wayBill.getWayBillNum())) {
				// 运单号查询
				QueryBuilder tempQuery = new TermQueryBuilder("wayBillNum", wayBill.getWayBillNum());
				query.must(tempQuery);
			}
			if (StringUtils.isNoneBlank(wayBill.getSendAddress())) {
				// 1.输入的内容为一个词条时
				QueryBuilder wildcardQuery = new WildcardQueryBuilder("sendAddress",
						"*" + wayBill.getSendAddress() + "*");

				// 2.输入的内容是一个分词的时候(多个词条组合)，,进行分词后 每个词条匹配查询
				QueryBuilder queryStringQueryBuilder = new QueryStringQueryBuilder(wayBill.getSendAddress())
						.field("sendAddress").defaultOperator(Operator.AND);

				// 两种情况取or
				BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
				boolQueryBuilder.should(wildcardQuery);
				boolQueryBuilder.should(queryStringQueryBuilder);

				query.must(boolQueryBuilder);
			}
			if (StringUtils.isNoneBlank(wayBill.getRecAddress())) {
				// 收货地 模糊查询
				QueryBuilder wildcardQuery = new WildcardQueryBuilder("recAddress",
						"*" + wayBill.getRecAddress() + "*");

				QueryBuilder queryStringQueryBuilder = new QueryStringQueryBuilder(wayBill.getRecAddress())
						.field("recAddress").defaultOperator(Operator.AND);

				// 两种情况取or
				BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
				boolQueryBuilder.should(wildcardQuery);
				boolQueryBuilder.should(queryStringQueryBuilder);

				query.must(boolQueryBuilder);
			}
			if (StringUtils.isNoneBlank(wayBill.getSendProNum())) {
				// 速运类型 等值查询
				QueryBuilder termQuery = new TermQueryBuilder("sendProNum", wayBill.getSendProNum());

				query.must(termQuery);
			}
			if (wayBill.getSignStatus() != null && wayBill.getSignStatus() != 0) {
				// 签收状态查询
				QueryBuilder termQuery = new TermQueryBuilder("signStatus", wayBill.getSignStatus());
				query.must(termQuery);
			}

			// 分页
			SearchQuery searchQuery = new NativeSearchQuery(query);
			searchQuery.setPageable(pageable);
			return wayBillIndexRepository.search(searchQuery);
		}

	}

	@Override
	public WayBill findByWayBillNum(String wayBillNum) {

		return wayBillRepository.findByWayBillNum(wayBillNum);
	}

	/*
	 * 同步索引库的方法
	 */
	@Override
	public void syncIndex() {
		List<WayBill> wayBills = wayBillRepository.findAll();
		wayBillIndexRepository.save(wayBills);
	}

	/*
	 * 导出Excel时根据条件查询,不分页
	 */
	@Override
	public List<WayBill> findWayBills(WayBill wayBill) {

		// 判断WayBill 中条件是否存在
		if (StringUtils.isBlank(wayBill.getWayBillNum()) && StringUtils.isBlank(wayBill.getSendAddress())
				&& StringUtils.isBlank(wayBill.getRecAddress()) && StringUtils.isBlank(wayBill.getSendProNum())
				&& (wayBill.getSignStatus() == null || wayBill.getSignStatus() == 0)) {
			// 无条件查询 、查询数据库
			return wayBillRepository.findAll();
		} else {
			// 无条件查询,查询索引库
			// 查询条件
			// must 条件必须成立 and
			// must not 条件必须不成立 not
			// should 条件可以成立 or
			BoolQueryBuilder query = new BoolQueryBuilder(); // 布尔查询 ，多条件组合查询
			// 向组合查询对象添加条件
			if (StringUtils.isNoneBlank(wayBill.getWayBillNum())) {
				// 运单号查询
				QueryBuilder tempQuery = new TermQueryBuilder("wayBillNum", wayBill.getWayBillNum());
				query.must(tempQuery);
			}
			if (StringUtils.isNoneBlank(wayBill.getSendAddress())) {
				// 1.输入的内容为一个词条时
				QueryBuilder wildcardQuery = new WildcardQueryBuilder("sendAddress",
						"*" + wayBill.getSendAddress() + "*");

				// 2.输入的内容是一个分词的时候(多个词条组合)，,进行分词后 每个词条匹配查询
				QueryBuilder queryStringQueryBuilder = new QueryStringQueryBuilder(wayBill.getSendAddress())
						.field("sendAddress").defaultOperator(Operator.AND);

				// 两种情况取or
				BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
				boolQueryBuilder.should(wildcardQuery);
				boolQueryBuilder.should(queryStringQueryBuilder);

				query.must(boolQueryBuilder);
			}
			if (StringUtils.isNoneBlank(wayBill.getRecAddress())) {
				// 收货地 模糊查询
				QueryBuilder wildcardQuery = new WildcardQueryBuilder("recAddress",
						"*" + wayBill.getRecAddress() + "*");

				QueryBuilder queryStringQueryBuilder = new QueryStringQueryBuilder(wayBill.getRecAddress())
						.field("recAddress").defaultOperator(Operator.AND);

				// 两种情况取or
				BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
				boolQueryBuilder.should(wildcardQuery);
				boolQueryBuilder.should(queryStringQueryBuilder);

				query.must(boolQueryBuilder);
			}
			if (StringUtils.isNoneBlank(wayBill.getSendProNum())) {
				// 速运类型 等值查询
				QueryBuilder termQuery = new TermQueryBuilder("sendProNum", wayBill.getSendProNum());

				query.must(termQuery);
			}
			if (wayBill.getSignStatus() != null && wayBill.getSignStatus() != 0) {
				// 签收状态查询
				QueryBuilder termQuery = new TermQueryBuilder("signStatus", wayBill.getSignStatus());
				query.must(termQuery);
			}

			// 不需要分页
			SearchQuery searchQuery = new NativeSearchQuery(query);
			Long count = wayBillIndexRepository.count();
			Pageable pageable = new PageRequest(0, count.intValue());
			searchQuery.setPageable(pageable);

			return wayBillIndexRepository.search(searchQuery).getContent();
		}

	}

}
